package ink.xiaobaibai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ink.xiaobaibai.autoConfig.roleResources.ResourcesRoleMapping;
import ink.xiaobaibai.common.MyRole;
import ink.xiaobaibai.entity.AdminRole;
import ink.xiaobaibai.entity.AdminUser;
import ink.xiaobaibai.entity.AdminUserRole;
import ink.xiaobaibai.response.ResponseCode;
import ink.xiaobaibai.response.ResponseFormat;
import ink.xiaobaibai.service.IAdminRoleService;
import ink.xiaobaibai.service.IAdminUserRoleService;
import ink.xiaobaibai.service.IAdminUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @description: 权限控制接口
 * @author: 小白白
 * @create: 2021-07-01
 **/

@Slf4j
@RestController
@RequestMapping("/security/power")
@CrossOrigin
@Api(tags = "权限控制接口(仅管理可操作)")
@ResourcesRoleMapping(resourceName = "权限控制接口", includeRoleNames = {MyRole.ADMIN})
public class SecurityPowerController {

    @Autowired
    private IAdminRoleService adminRoleService;

    @Autowired
    private IAdminUserService adminUserService;

    @Autowired
    private IAdminUserRoleService adminUserRoleService;

    /**
     * 查看当前所有角色
     */
    @GetMapping("/roles")
    @ApiOperation("查看当前所有角色(非基础角色)")
    public ResponseFormat getRoles() {
        QueryWrapper<AdminRole> q1 = new QueryWrapper<>();
        q1.notIn("role_name", MyRole.AGENT, MyRole.DISTRIBUTOR, MyRole.ADMIN);
        List<AdminRole> list = this.adminRoleService.list(q1);
        return ResponseFormat.success(list);
    }

    /**
     * 查看当前用户绑定的角色
     */
    @GetMapping("/user/{userId}")
    @ApiOperation("根据用户id查看当前用户的角色")
    public ResponseFormat getRolesByUserId(@PathVariable("userId") Integer userId) {
        return ResponseFormat.success(this.adminUserService.getRoleListByUserId(userId));
    }

    /**
     * 为用户绑定角色 [基础角色和额外角色分开来]
     */
    @PostMapping("/bind")
    @ApiOperation("为用户绑定角色[非基础角色,是权限角色]")
    public ResponseFormat bindUserRole(@RequestParam("userId") Integer userId,
                                       @RequestParam("roleId") Integer roleId) {
        // 内部已经限定,不可操作基础角色
        ResponseFormat valid = this.valid(userId, roleId);
        if (valid.getCode() == ResponseCode.ERROR.getCode()) {
            return valid;
        }
        String roleName = (String) valid.getData();
        List<String> roleListByUserId = this.adminUserService.getRoleListByUserId(userId);
        if (roleListByUserId.contains(roleName)) {
            return ResponseFormat.fail("已经包含此角色了");
        }
        this.adminUserRoleService.save(new AdminUserRole(userId, roleId));
        return ResponseFormat.success();
    }

    /**
     * 为用户解绑一个角色
     */
    @PostMapping("/unbind")
    @ApiOperation("为一个用户解绑角色")
    public ResponseFormat unbindRole(@RequestParam("userId") Integer userId,
                                     @RequestParam("roleId") Integer roleId) {
        // 内部已经限定,不可操作基础角色
        ResponseFormat valid = this.valid(userId, roleId);
        if (valid.getCode() == ResponseCode.ERROR.getCode()) {
            return valid;
        }
        QueryWrapper<AdminUserRole> q1 = new QueryWrapper<>();
        q1.eq("user_id", userId);
        q1.eq("role_id", roleId);
        this.adminUserRoleService.remove(q1);
        return ResponseFormat.success();
    }

    private ResponseFormat valid(Integer userId,
                                 Integer roleId) {
        //当前用户和角色不存在
        QueryWrapper<AdminUser> q1 = new QueryWrapper<>();
        q1.eq("id", userId);
        if (this.adminUserService.count(q1) == 0) {
            return ResponseFormat.fail("当前用户不存在");
        }
        AdminRole adminRole = this.adminRoleService.getById(roleId);
        if (adminRole == null) {
            return ResponseFormat.fail("当前角色不存在");
        }
        if (adminRole.getRoleName().equals(MyRole.AGENT) || adminRole.getRoleName().equals(MyRole.ADMIN) || adminRole.getRoleName().equals(MyRole.DISTRIBUTOR)) {
            return ResponseFormat.fail("不可操作基础角色");
        }
        return ResponseFormat.success(adminRole.getRoleName());
    }

}
